package org.leo.funny.autoconfigure;

import org.leo.funny.io.WriterTemplate;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnSingleCandidate;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.io.File;
import java.io.FileNotFoundException;
import java.nio.charset.Charset;
import java.sql.SQLException;

@Configuration
// 当 WriterTemplate 类存在时配置生效
@ConditionalOnClass(WriterTemplate.class)
// 启用 FunnyProperties 属性处理类
@EnableConfigurationProperties(FunnyProperties.class)
// 让该自动配置位于 DataSourceAutoConfiguration 自动配置之后处理
@AutoConfigureAfter(DataSourceAutoConfiguration.class)
public class FunnyAutoConfiguration {
    // FunnyProperties类负责加载配置属性
    private final FunnyProperties properties;

    public FunnyAutoConfiguration(FunnyProperties properties) {
        this.properties = properties;
    }

    @Bean(destroyMethod = "close")
    // 当单例的 DataSource Bean 存在时，配置生效
    @ConditionalOnSingleCandidate(DataSource.class)
    // 当容器中没有 WriterTemplate Bean 时，配置生效
    @ConditionalOnMissingBean
    // 通过 @AutoConfigureOrder 注解指定该配置方法
    // @AutoConfigureOrder 注解指定的数值越小，配置方法的优先级越高
    @AutoConfigureOrder(99)
    public WriterTemplate writerTemplate(DataSource dataSource) throws SQLException {
       return new WriterTemplate(dataSource);
    }

    @Bean(destroyMethod = "close")
    // 当前面的 WriterTemplate 配置没有生效时，该方法的配置才会生效
    @ConditionalOnMissingBean
    @AutoConfigureOrder(199)
    public WriterTemplate writerTemplate2() throws FileNotFoundException {
        File file = new File(this.properties.getDest());
        Charset charset = Charset.forName(this.properties.getCharset());
        return new WriterTemplate(file, charset);
    }
}
